package com.server.common.security.code;

import com.server.model.all.constant.token.TokenConstant;
import com.server.common.code.error.BusinessException;
import com.server.common.code.utils.GsonUtils;
import com.server.common.code.vo.LoginVo;
import com.server.common.security.code.thread.ThreadLocalHeaderUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * 权限获取工具类
 * 
 */
@Slf4j
public class SecurityUtils
{
    /**
     * 复用
     * @author LXC
     * @date 2022-07-25 15:49
     */
    public static String getHeader(String key){
        HttpServletRequest request = ServletUtils.getRequest();

        if(!ObjectUtils.isEmpty(request)){
            return request.getHeader(key);
        }

        return ThreadLocalHeaderUtils.getHeader(key);
    }

    /**
     * 获取用户信息
     */
    public static LoginVo getLoginVo()
    {
        String header = getHeader(TokenConstant.TOKEN_JSON_DATA);

        //
        if(ObjectUtils.isEmpty(header)){
            return new LoginVo();
        }

        return GsonUtils.getGson().fromJson(header, LoginVo.class);
    }

    /**
     * 获取IP
     * @author LXC
     * @date 2023/2/3 10:51
     */
    public static String getIpAddress(){
        HttpServletRequest request = ServletUtils.getRequest();
        try {
            String ipAddress = SecurityUtils.getHeader("x-forwarded-for");

            if (ObjectUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = SecurityUtils.getHeader("Proxy-Client-IP");
            }
            if (ObjectUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = SecurityUtils.getHeader("WL-Proxy-Client-IP");
            }
            if (ObjectUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if ("127.0.0.1".equals(ipAddress)) {
                    ipAddress = InetAddress.getLocalHost().getHostAddress();
                }
            }
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }

            return ipAddress;
        } catch (Exception e) {
            log.error("获取失败",e);
        }
        throw new BusinessException("获取失败");
    }




}
